const service = require("../service/service.js")
const operation = require("../service/operation.js")
const ISTOKEN = false;
const mysqldb = require("../util/db.js")

var resmsg = {
    status: true,
    data: []
}
exports.controller = function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    let params = new Object()
    params.cmd = req.params.cmd
    params.param = req.body || req.query
    console.log(params)
    if (ISTOKEN) {
        if (params.param.UID && params.param.TOKEN) {
            provingtoken(params.param.UID, params.param.TOKEN, (ret) => {
                if (ret == 1) {
                    console.log(params.param.UID + "验证成功")
                    service.service(params, (err, result) => {
                        err ? resmsg.status = true : resmsg.status = false;
                        resmsg.data = result;
                        res.send(resmsg)
                    })
                } else {
                    res.send("TOKEN 验证失败")
                }
            })
        } else {
            res.send("UID or TOKEN 无效！")
        }
    } else {
        service.service(params, (err, result) => {
            err ? resmsg.status = true : resmsg.status = false;
            resmsg.data = result;
            res.send(resmsg)
        })
    }
}


const provingtoken = function (Userid, Token, cb) {
    var db = new mysqldb.db()
    var ret = -1;
    if (!Userid || !Token) {
        cb && cb(ret);
    } else {
        var sql = "select count(*) as totals from sys_user where UID= " + Userid + " and TOKEN = " + Token
        db.getAll(sql, (err, data) => {
            if (err && err.status < 0) {
                console.log(err)
            } else if (data[0].totals > 0) {
                ret = 1
                cb && cb(ret);
            } else {
                ret = 0
                cb && cb(ret);
            }
        })
    }
}


exports.operation = function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    var type = req.params.operation;
    var param = req.body || req.query
    operation.operation(type, param, (result) => {
        res.json(result)
    })
}